/**
 * Copyright © 2020 易久批信息技术有限公司. All rights reserved.
 */
package com.dysm.loan;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 等额本金计算
 * @author xiay
 * @since 2020/12/3 9:45 上午
 */
public class StandOfCapitalCal implements InterestCalculate {

    /**
     * 等额本金
     * @param totalAmount
     * @param monthNum
     * @param yearRate
     */
    @Override
    public void calculate(BigDecimal totalAmount, BigDecimal monthNum, BigDecimal yearRate) {
        BigDecimal monthRate = yearRate.divide(BigDecimal.valueOf(12), 6, RoundingMode.HALF_UP);
        BigDecimal monthCapitalAmount = totalAmount.divide(monthNum, 6, RoundingMode.HALF_UP);
        int monthInt = monthNum.intValue();
        BigDecimal totalInterest = BigDecimal.ZERO;
        BigDecimal remainAmount = totalAmount;
        System.err.println("--------等额本金开始还款--------");
        for (Integer i = 1; i <= monthInt; i++) {
            BigDecimal currentInterest = monthCapitalAmount.multiply(BigDecimal.valueOf(monthInt - i + 1)).multiply(monthRate);
            BigDecimal currentRePayAmount = monthCapitalAmount.add(currentInterest);
            remainAmount = remainAmount.subtract(monthCapitalAmount);
            String repayMsg = String.format("第【%s】期还款：【%.2f】，本金：【%.2f】，利息：【%.2f】，剩余本金：【%.2f】",
                    i, currentRePayAmount, monthCapitalAmount, currentInterest, remainAmount);
            System.out.println(repayMsg);
            totalInterest = totalInterest.add(currentInterest);
        }
        String titleMsg = String.format("当前贷款总额：【%s】，年利率：【%s】，还款期数：【%s】，利息总额：【%.2f】",
                totalAmount, yearRate, monthNum, totalInterest);
        System.out.println(titleMsg);
        System.err.println("--------等额本金结束还款--------");
    }
}
